﻿
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Wasion.HHU.Data.Models;
using Wasion.HHU.Data.Repositories;
using SQLite.Net;

namespace Wasion.HHU.Data.Repositories
{
    public class ProtocolDbRepository : BaseDbRepository
    {
        public ProtocolDbRepository():base()
        {

        }
        public ProtocolDbRepository(SQLiteConnection connection)
            : base(connection)
        {
        }

        public List<CaptureObjs> GetByObAttrID(string obAttrID)
        {
            List<CaptureObjs> list;
            lock (databaseLock)
            {
                list = DbConnection.Table<CaptureObjs>().Where(w=>w.ObAttrID == obAttrID).ToList();
            }

            return list;
        }

        public Task<List<CaptureObjs>> GetAllCaptureObjs()
        {
            List<CaptureObjs> list;

            lock (databaseLock)
            {
                list = DbConnection.Table<CaptureObjs>().OrderBy(x => x.ObAttrID).ThenBy(x => x.seq).ToList();
            }
            return Task.FromResult(list);
        }

        public int Insert(CaptureObjs objs)
        {
            lock (databaseLock)
            {
                DbConnection.CreateTable<CaptureObjs>();
                return DbConnection.Insert(objs);
            }
        }

        public int Update(CaptureObjs objs)
        {
            lock (databaseLock)
            {
                return DbConnection.Update(objs);
            }
        }

        public int Delete(string sid, bool isAll)
        {
            lock (databaseLock)
            {
                //DbConnection.Delete<CaptureObjs>(primaryKey);
                if (isAll)
                {
                    return DbConnection.Table<CaptureObjs>().Delete(d => d.ObAttrID == sid);
                }
                else
                {
                    return DbConnection.Table<CaptureObjs>().Delete(d => d.ObAttrID == sid && d.IfStatic != 1);
                }
            }
        }

        public CaptureObjs Find(string obattrid,string relateattrid,int dataindex)
        {
            lock (databaseLock)
            {
                var obj = DbConnection.FindWithQuery<CaptureObjs>(
                    "select * from T_CaptureObjs where ObAttrID = ? and RelateAttrID = ? and DataIndex = ?", obattrid, relateattrid, dataindex);

                return obj;
            }
        }

        public int GetNewSEQ(string sid)
        {
            var seq = DbConnection.Table<CaptureObjs>().Where(w => w.ObAttrID == sid).Select(s=>s.seq).FirstOrDefault();
            return seq + 1;
        }

        public Task<List<MeterTypeRole>> GetAllMeterTypeRole()
        {
            List<MeterTypeRole> list;

            lock (databaseLock)
            {
                list = DbConnection.Table<MeterTypeRole>().OrderBy(x => x.MtypeID).ThenBy(x => x.RoleClientAddr).ToList();
            }
            return Task.FromResult(list);
        }
    }
}
